package com.sqfw.project.largeScreen.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.sqfw.common.utils.DateUtils;
import com.sqfw.common.utils.PageUtils;
import com.sqfw.framework.redis.RedisCache;
import com.sqfw.framework.web.domain.AjaxResult;
import com.sqfw.framework.web.domain.R;
import com.sqfw.project.knowledge.domain.KlContentInfo;
import com.sqfw.project.knowledge.mapper.KlContentInfoMapper;
import com.sqfw.project.knowledge.service.KlContentService;
import com.sqfw.project.largeScreen.domain.LargeScreen;
import com.sqfw.project.largeScreen.domain.query.LargeScreenQuery;
import com.sqfw.project.largeScreen.mapper.WpInfoCountMapper;
import com.sqfw.project.largeScreen.service.LargeScreenService;
import com.sqfw.project.system.domain.SysDept;
import com.sqfw.project.system.mapper.SysDeptMapper;
import com.sqfw.project.wp.domain.SysCode;
import com.sqfw.project.wp.domain.WpInfo;
import com.sqfw.project.wp.mapper.SysCodeMapper;
import com.sqfw.project.wp.mapper.WpInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 大屏幕接口 ServiceImpl
 *
 * @author tangxt
 * */
@Slf4j
@Service
public class LargeScreenServiceImpl implements LargeScreenService {

    @Autowired
    private WpInfoMapper wpInfoMapper;

    @Autowired
    private WpInfoCountMapper wpInfoCountMapper;

    @Autowired
    private SysCodeMapper sysCodeMapper;

    @Autowired
    private KlContentInfoMapper klContentInfoMapper;

    @Autowired
    private KlContentService klContentService;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private RedisCache redisCache;

    private final static String[] class2Arr = {"养老服务", "基层政权", "社会组织管理", "区划地名", "婚姻登记管理"};
    private final static String[] class3Arr = {"养老机构", "社团管理", "国内婚姻", "养老服务补贴", "助餐点"};

    private final static String AREA_CODE = "247";

    private final static String[] scidTypeArr1 = {"12345工单", "110接警", "一网通办系统", "在线帮办"};
    private final static String[] scidTypeArr2 = {"弹屏建单", "手工建单"};

    private final static String SATISFIED = "满意";
    private final static String DISSATISFIED = "不满意";
    private final static String GENERAL = "一般";

    @Override
    public AjaxResult countWpByClassify(LargeScreenQuery query) {
        Object cacheObject = redisCache.getCacheObject("largeScreen:countWpByClassify:"+query.getTimeLevel());
        if (ObjectUtil.isNotEmpty(cacheObject)) {
            return AjaxResult.success(cacheObject);
        }
        setCreateTime(query);
        if (!query.getPageNumber().equals(0)) {
            query.setPageNumber((query.getPageNumber() - 1) * query.getPageSize());
        }
//        if (StringUtils.isBlank(query.getNextState())) {
//            query.setNextState("工单归档");
//        }

        List<LargeScreen> countClass2List = wpInfoCountMapper.countWpByClass2(query);
        List<LargeScreen> countClass3List = wpInfoCountMapper.countWpByClass3(query);

        List<Long> class2Ids = new ArrayList<>();
        if (!CollectionUtils.isEmpty(countClass2List)) {
            class2Ids = countClass2List.stream().map(c ->{
                return Long.parseLong(c.getClassifyId());
            }).collect(Collectors.toList());
        }
        if (!CollectionUtils.isEmpty(countClass3List)) {
            List<Long> class3Ids = countClass3List.stream().map(c ->{
                return Long.parseLong(c.getClassifyId());
            }).collect(Collectors.toList());
            class2Ids.addAll(class3Ids);
        }
        // 查询分类名称
        List<SysCode> sysCodes = new ArrayList<>();
        if (!CollectionUtils.isEmpty(class2Ids)) {
            sysCodes = sysCodeMapper.selectSysCodeByAutoIds(class2Ids);
        }
        Map<String, List<LargeScreen>> resultMap = new HashMap<>(6);
        if (!CollectionUtils.isEmpty(countClass2List)) {
            resultMap.put("CLASS2", getCountClassList(countClass2List, sysCodes, class2Arr));
        }else {
            resultMap.put("CLASS2", countClass2List);
        }
        if (!CollectionUtils.isEmpty(countClass3List)) {
            resultMap.put("CLASS3", getCountClassList(countClass3List, sysCodes, class3Arr));
        }else {
            resultMap.put("CLASS3", countClass3List);
        }

        redisCache.setCacheObject("largeScreen:countWpByClassify:" + query.getTimeLevel(), resultMap, 3, TimeUnit.MINUTES);
        return AjaxResult.success(resultMap);
    }

    @Override
    public AjaxResult countWpByFiveMajorModules(LargeScreenQuery query) {
        setCreateTime(query);
        if (!query.getPageNumber().equals(0)) {
            query.setPageNumber((query.getPageNumber() - 1) * query.getPageSize());
        }
        //20240117洪磊改
//        if (StringUtils.isBlank(query.getNextState())) {
//            query.setNextState("工单归档");
//        }
        Map<String, List<LargeScreen>> resultMap = new HashMap<>(6);
        List<LargeScreen> countClass5List = wpInfoCountMapper.countWpByFiveMajorModules(query);
        List<LargeScreen> fiveMajorModules = new ArrayList<>();
        if (countClass5List != null) {
            List<String> fiveMajorModulesList = wpInfoCountMapper.getFiveMajorModules();
            for (String five : fiveMajorModulesList) {
                boolean isFive = true;
                for (LargeScreen largeScreen : countClass5List) {
                    if (five.trim().equals(largeScreen.getClassifyName())) {
                        fiveMajorModules.add(largeScreen);
                        isFive = false;
                        break;
                    }
                }
                if (isFive) {
                    fiveMajorModules.add(new LargeScreen(five.trim(), 0));
                }
            }
        }
        resultMap.put("FIVE_MAJOR_MODULES", fiveMajorModules);
        return AjaxResult.success(resultMap);
    }

    @Override
    public List<KlContentInfo> queryLargeScreenKnowledge(LargeScreenQuery query) {
        KlContentInfo klContentInfo = new KlContentInfo();
        klContentInfo.setKlContentStatus("1");
        klContentInfo.setKlContentValiditytime(new Date());
        List<KlContentInfo> klContentInfoList = klContentInfoMapper.queryLargeScreenKnowledge(klContentInfo);
        return klContentInfoList;
    }

    @Override
    public AjaxResult countWpTotal(LargeScreenQuery query) {
        Map<String, Object> countMap = new HashMap<>(16);
        setCreateTime(query);
//        if (StringUtils.isBlank(query.getScidType())) {
//            query.setScidType("12345工单");
//        }
//        int countReceive = wpInfoCountMapper.countWpInfoByScidType(query);
        // 统计流转工单
        query.setEndState("流转");
        int countReceive = wpInfoCountMapper.countWpByEndState(query);
//        String newString = String.format("%05d", countReceive);
        // 12345工单总数
        countMap.put("COUNT_12345_TOTAL", countReceive);
        // 统计自办工单
//        if (StringUtils.isBlank(query.getEndState())) {
//            query.setEndState("自办");
//        }
        query.setEndState("自办");
        int countSelfNumber = wpInfoCountMapper.countWpByEndState(query);
        // 自办总数
        countMap.put("COUNT_SELF_TOTAL", countSelfNumber);

        // 建单数：改为工单量（包含所有工单来源，去除弹屏建单）
        query.setScidType(null);
        int countCreateTotal = wpInfoCountMapper.countWpByScidTypeNot(query);
        // 工单量
        countMap.put("COUNT_CREATE_TOTAL", countCreateTotal);

        // 统计拨出数量（平台呼出量）
        query.setCallType("拨出");
        int countExhalation = wpInfoCountMapper.countZjRecordInfoByCallType(query);
        // 呼出数改为：平台呼出量（呼出成功量）
        countMap.put("COUNT_EXHALATION_TOTAL", countExhalation);

        // 工单总数：改为工作总量=建单数：改为工单量（包含所有工单来源，去除弹屏建单）+呼出数：改呼出量（呼出成功量）
        countMap.put("COUNT_WP_TOTAL", countCreateTotal + countExhalation);

        return AjaxResult.success(countMap);
    }

    @Override
    public AjaxResult countWpByMainUnit(LargeScreenQuery query) {
        setCreateTime(query);
        List<LargeScreen> largeScreenList = wpInfoCountMapper.countWpByMainUnit(query);
        String mainUnitId = query.getMainUnitLike();
        SysDept dept = new SysDept();
        dept.setParentId(Long.parseLong(mainUnitId));
        List<SysDept> deptList = deptMapper.selectDeptList(dept);
        List<LargeScreen> countList = new ArrayList<>();
        for (SysDept sysDept : deptList) {
            String deptName = sysDept.getDeptName();
            if (AREA_CODE.equals(query.getMainUnitLike())) {
                deptName = sysDept.getDeptName().replace("民政局", "");
            }
            boolean isNoData = true;
            LargeScreen count = new LargeScreen();
            String deptId = query.getMainUnitLike() + "," + sysDept.getDeptId();
            for (LargeScreen largeScreen : largeScreenList) {
                if (deptId.equals(largeScreen.getMainUnit())) {
                    count.setMainUnit(deptId);
                    count.setCountNumber(largeScreen.getCountNumber());
                    count.setCountMainUnitNumber(String.format("%05d", largeScreen.getCountNumber()));
                    count.setMainUnitName(deptName);
                    isNoData = false;
                    break;
                }
            }
            if (isNoData) {
                count.setMainUnit(deptId);
                count.setMainUnitName(deptName);
                count.setCountNumber(0);
            }
            countList.add(count);
        }
        return AjaxResult.success(countList);
    }

    @Override
    public AjaxResult countTimeoutAndDissatisfied(LargeScreenQuery query) {
        Map<String, Object> countMap = new HashMap<>(6);
        query.setDeptId(query.getMainUnitLike().split(",")[1]);
        String newString = String.format("%05d", query.getCountNumber());
        // 工单总数
        countMap.put("COUNT_TOTAL", newString);
        int countTimeout = wpInfoCountMapper.countTimeoutWpByDeptId(query);
        // 超时办结总数
        countMap.put("COUNT_TIMEOUT", String.format("%05d", countTimeout));
        query.setIsSatisfied("不满意");
        int dissatisfied = wpInfoCountMapper.countWpVisitInfoByDeptId(query);
        // 不满意总数
        countMap.put("COUNT_DISSATISFIED", String.format("%05d", dissatisfied));
        return AjaxResult.success(countMap);
    }

    @Override
    public AjaxResult countWpVisitInfoByGrouping(LargeScreenQuery query) {
        Map<String, Object> visitMap = new HashMap<>();
        setCreateTime(query);
        List<LargeScreen> visitList = wpInfoCountMapper.countWpVisitInfoByGrouping(query);
        // 满意
        int countSatisfied = 0;
        // 不满意
        int countDissatisfied = 0;
        // 一般
        int countGeneral = 0;
        for (LargeScreen visit : visitList) {
            // 满意
            if (SATISFIED.equals(visit.getVisitType())) {
                countSatisfied = visit.getCountNumber();
                continue;
            }
            // 不满意
            if (DISSATISFIED.equals(visit.getVisitType())) {
                countDissatisfied = visit.getCountNumber();
                continue;
            }
            // 一般
            if (GENERAL.equals(visit.getVisitType())) {
                countGeneral = visit.getCountNumber();
            }
        }
        int visitTotal = countSatisfied + countDissatisfied + countGeneral;
        visitMap.put("VISIT_TOTAL", visitTotal);
        visitMap.put("SATISFIED", countSatisfied);
        visitMap.put("DISSATISFIED", countDissatisfied);
        visitMap.put("GENERAL", countGeneral);
        visitMap.put("SATISFIED_RATE", getPercent(countSatisfied + countGeneral, visitTotal));
        return AjaxResult.success(visitMap);
    }

    @Override
    public List<WpInfo> getRealTimeWpInfoList(LargeScreenQuery query) {
        List<WpInfo> wpInfoList = wpInfoCountMapper.selectRealTimeWpInfoList(query);
        List<Long> class2Ids = new ArrayList<>();
        if (!CollectionUtils.isEmpty(wpInfoList)) {
            Set<Long> class2Set = new HashSet<>();
            for (WpInfo info : wpInfoList) {
                if (StringUtils.isNotBlank(info.getClass2())) {
                    class2Set.add(Long.parseLong(info.getClass2()));
                }
            }
            if (!CollectionUtils.isEmpty(class2Set)) {
                class2Ids.addAll(class2Set);
            }
        }
        // 查询分类名称
        List<SysCode> sysCodes = new ArrayList<>();
        if (!CollectionUtils.isEmpty(class2Ids)) {
            sysCodes = sysCodeMapper.selectSysCodeByAutoIds(class2Ids);
        }
        if (!CollectionUtils.isEmpty(wpInfoList)) {
            for (WpInfo wpInfo : wpInfoList) {
                wpInfo.setCustomerName(nameDesensitize(wpInfo.getCustomerName()));
                for (SysCode sysCode : sysCodes) {
                    if (StringUtils.isNotBlank(wpInfo.getClass2()) &&
                            wpInfo.getClass2().equals(String.valueOf(sysCode.getAutoId()))) {
                        wpInfo.setSummary(sysCode.getNodename());
                        break;
                    }
                }
            }
        }
        return wpInfoList;
    }

    private  List<LargeScreen> getCountClassList(List<LargeScreen> countClassList,
                                                 List<SysCode> sysCodes,
                                                 String[] classArr) {
        List<LargeScreen> countClass2s = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            if (i < countClassList.size()) {
                LargeScreen largeScreen = countClassList.get(i);
                for (SysCode sysCode : sysCodes) {
                    if (largeScreen.getClassifyId().equals(String.valueOf(sysCode.getAutoId()))) {
                        largeScreen.setClassifyName(sysCode.getNodename());
                        countClass2s.add(largeScreen);
                        break;
                    }
                }
            }else {
                for (int j = 0; j < classArr.length; j++) {
                    boolean isClass = true;
                    String classStr = classArr[j];
                    for (LargeScreen cl : countClass2s) {
                        if (classStr.equals(cl.getClassifyName())) {
                            isClass = false;
                        }
                    }
                    if (isClass) {
                        countClass2s.add(new LargeScreen(classStr, 0));
                        break;
                    }
                }
            }
        }
        return countClass2s;
    }

    private void setCreateTime(LargeScreenQuery query) {
        Date date = DateUtils.getNowDate();
        query.setStartCreateTime(DateUtils.dateTime(DateUtils.plusOrMinusMonth(date, query.getTimeLevel())));
        query.setEndCreateTime(DateUtils.dateTime(date));
    }



    /**
     * 方式一：使用java.text.NumberFormat实现
     * @param x
     * @param y
     * @return
     */
    public static String getPercent(int x, int y) {
        double d1 = x * 1.0;
        double d2 = y * 1.0;
        NumberFormat percentInstance = NumberFormat.getPercentInstance();
        // 设置保留几位小数，这里设置的是保留两位小数
        percentInstance.setMinimumFractionDigits(2);
        return percentInstance.format(d1 / d2);
    }

    /**
     * 姓名脱敏
     * */
    private String nameDesensitize(String name) {
        if (StringUtils.isBlank(name)) {
            return "";
        }
        name = name.trim();
        //定义脱敏后的姓名
        String resultName = "";
        if (name.length() == 1) {
            //张 -> 张
            resultName = name;
        }
        if (name.length() == 2) {
            //张三 -> 张*
            resultName = name.replaceFirst(name.substring(1), "*");
        }
        if (name.length() > 2) {
            String asterisk = "";
            int i = name.length() - 2;
            for (int k = 0; k < i; k++) {
                asterisk += "*";
            }
            //张三丰 -> 张*丰
            resultName = name.charAt(0) + asterisk + name.charAt(name.length() - 1);
        }
        if (StringUtils.isNotBlank(resultName)) {
            return resultName;
        }
        return name;
    }


}
